package com.share.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.domain.SysMenu;
import com.share.domain.SysUser;
import com.share.dto.SysMenuDto;
import com.share.mapper.SysUserMapper;
import com.share.service.SysMenuService;
import com.share.mapper.SysMenuMapper;
import com.share.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserMapper sysUserMapper;


    public List<SysMenu> buildTreeMenu(List<SysMenu> menuList) {
        List<SysMenu> resultMenuList = new ArrayList<>();
        for (SysMenu sysMenu:menuList){

            //寻找子节点
            for (SysMenu menu : menuList) {
                if (menu.getParentId()==sysMenu.getId()){
                    sysMenu.getChildren().add(menu);
                }
            }

            if (sysMenu.getParentId()==0L){
                resultMenuList.add(sysMenu);
            }
        }
        return resultMenuList;
    }



    public List<SysMenuDto> getCurrentUserNav() {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserService.getByUsername(username);

        List<Long> menuIds = sysUserMapper.getNavMenuIds(sysUser.getId());
        List<SysMenu> menus = this.listByIds(menuIds);

        //转树状结构
        List<SysMenu> menuTree = buildTreeMenu(menus);

        //实体DTO

        return convert(menuTree);
    }


    public List<SysMenu> tree() {
        //获取所有菜单信息
        List<SysMenu> menus = this.list(new QueryWrapper<SysMenu>().orderByAsc("orderNum"));
        //转成树状结构

        return buildTreeMenu(menus);
    }


    private List<SysMenuDto> convert(List<SysMenu> menuTree) {

        List<SysMenuDto> menuDtos = new ArrayList<>();
        menuTree.forEach(m->{
            SysMenuDto dto = new SysMenuDto();
            dto.setId(m.getId());
            dto.setName(m.getPerms());
            dto.setTitle(m.getName());
            dto.setComponent(m.getComponent());
            dto.setPath(m.getPath());
            if (m.getChildren().size()>0){
                dto.setChildren(convert(m.getChildren()));
            }
            menuDtos.add(dto);
        });

        return menuDtos;
    }
}




